<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

class CoreCaptcha {
	//
	var $session_sname = 'checkcode';
	//
	var $image_width = 120;
	var $image_height = 40;
	var $image_type = 'jpg';
	
	//constructor
	function CoreCaptcha() {
		
	}
	
	//methods
	function generate_image($code = '') {
		if( $code == '' ) {
			$code = $this->generate_code();
		}
		
		//
		$this->_session_scode($code);
		
		//
		if( function_exists('imagecreatetruecolor') ) {
			$im_dest = imagecreatetruecolor($this->image_width, $this->image_height);
		} elseif( function_exists('imagecreate') ) {
			$im_dest = imagecreate($this->image_width, $this->image_height);
		}
		
		//imagecreatefromjpeg
		//imagecreatefromgif
		//imagesx, imagesy
		//imagecopyresampled
		//imagecopyresized
		
		//imagefontwidth
		//imagefontheight
		
		$im_color = imagecolorallocate($im_dest, 0, 0, 0);
		$im_length = strlen($code);
		$x = ceil(($this->image_width - imagefontwidth(5) * $im_length)/2);
		$x = ceil(($this->image_height - imagefontwidth(5))/2);
		
		imagestring($im_dest, 5, $x, $y, $code, $im_color);
		
		//
		header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
		header('Cache-Control: private, no-store, no-cache, must-revalidate');
		header('Cache-Control: post-check=0, pre-check=0, max-age=0', false);
		header('Pragma: no-cache');
		
		//
		if( $this->image_type == 'jpg' && function_exists('imagecreatefromjpeg') ) {
			header('Content-type: image/jpeg');
			imageinterlace($im_dest, 1);
			imagejpeg($im_dest, false, 90);
		} else {
			header('Content-type: image/png');
			imagepng($im_dest);
		}
		
		//
		imagedestroy($im_dest);
		
		return true;
	}
	
	function generate_code() {
		$code = strtoupper(util_create_random_value('4', 'chars'));
		
		return $code;
	}
	
	//
	function check($code) {
		return $this->_check_code($code);
	}
	
	//
	function _check_code($code) {
		$session_scode = isset($_SESSION[$this->session_sname]) ? $_SESSION[$this->session_sname] : '';
		
		if( $code == $session_scode ) {
			return true;
		}
		
		return false;
	}
	
	function _session_scode($code) {
		$_SESSION[$this->session_sname] = $code;
	}
}
//
?>